import {decrptParam} from '@/base/AesEncrptUtil.js'
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
const ASCII_CHARS = /[\x00-\xff]+/g;
/**
 * 将日期转换成指定的格式，如dateFormat(new Date(),"yyyy-MM-dd hh:mm:ss") ==> 2019-07-02 08:09:04
 * @param {日期} val
 * @param {转换后的格式} fmt
 */
export function dateFormat(val,fmt) {
    if(isNaN(val) && !isNaN(Date.parse(val))){
       return val
    }

    let o = {
        "M+": val.getMonth() + 1, //月份
        "d+": val.getDate(), //日
        "h+": val.getHours(), //小时
        "m+": val.getMinutes(), //分
        "s+": val.getSeconds(), //秒
        "q+": Math.floor((val.getMonth() + 3) / 3), //季度
        "S+": val.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o){
        if (new RegExp("(" + k + ")").test(fmt)) {
          if(k === 'S+'){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("000" + o[k]).substr(("" + o[k]).length)));
          } else {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          }
        }
    }
    return fmt;
}

/**
 * 将字符串转成日期格式
 * {@param {可以是日期格式  也可以是字符串格式yyyy-MM-dd、yyyyMMdd、yyyy/MM/dd}} param
 */
export function chgStrToDate(param,needHmi){
  let retDate;
  if(param instanceof Date){
    if(needHmi){
      return new Date(param.getFullYear(),param.getMonth(),param.getDate(),param.getHours(),param.getMinutes(),param.getSeconds());
    }else {
      return new Date(param.getFullYear(),param.getMonth(),param.getDate());
    }
  } else {
    let dateStr = param.replace(/-|\//g,'');
    let year = parseInt(dateStr.substr(0,4));
    let month = parseInt(dateStr.length > 4 && dateStr.substr(4,2))-1;
    let day = parseInt(dateStr.length > 6 && dateStr.substr(6,2));
    if(dateStr.length > 8){//还有时分秒
      dateStr = dateStr.replace(/:|\s+/g,'');
      let h = parseInt(dateStr.length > 8 && dateStr.substr(8,2)) || 0;
      let m = parseInt(dateStr.length > 10 && dateStr.substr(10,2)) || 0;
      let s = parseInt(dateStr.length > 12 && dateStr.substr(12,2)) || 0;
      retDate = new Date(year,month,day,h,m,s)
    }else {
      retDate = new Date(year,month,day)
    }
  }
  return retDate;
}
/**
 * 比较两个日期 aparam 比 bparam大返回1  小返回-1 相等返回0
 * @param {可以是日期格式  也可以是字符串格式yyyy-MM-dd、yyyyMMdd、yyyy/MM/dd} aparam
 * @param {可以是日期格式  也可以是字符串格式yyyy-MM-dd、yyyyMMdd、yyyy/MM/dd}  bparam
 */
export function cmpDateOrStr(aparam,bparam){
  let retCode = 0;
  let adate = chgStrToDate(aparam)
  let bdate = chgStrToDate(bparam);
  if(adate > bdate){
    retCode = 1;
  }else if(adate < bdate){
    retCode = -1;
  }else {
    retCode = 0;
  }

  return retCode;
}
export function getRect(el) {
    if (el instanceof window.SVGElement) {
      let rect = el.getBoundingClientRect()
      return {
        top: rect.top,
        left: rect.left,
        width: rect.width,
        height: rect.height
      }
    } else {
      return {
        top: el.offsetTop,
        left: el.offsetLeft,
        width: el.offsetWidth,
        height: el.offsetHeight
      }
    }
  }

  export function imageIsExist(url){
    return new Promise((resolve) => {
      var img = new Image();
      img.onload = function () {
          if (this.complete == true){
              resolve(true);
              img = null;
          }
      }
      img.onerror = function () {
          resolve(false);
          img = null;
      }
      img.src = url;
    });
  }


  export function addClass(el, className) {

    if(!el){
      return;
    }
    el.classList.add(className);
  }
  export function removeClass(el, cls) {
    if (!el || !cls) return;
    var classes = cls.split(' ');
    var curClass = ' ' + el.className + ' ';

    for (var i = 0, j = classes.length; i < j; i++) {
      var clsName = classes[i];
      if (!clsName) continue;

      if (el.classList) {
        el.classList.remove(clsName);
      } else {

      }
    }
    if (!el.classList) {
      el.className = trim(curClass);
    }
  };
  export const getStyle = function(element, styleName) {
      if (!element || !styleName) return null;
      styleName = camelCase(styleName);
      if (styleName === 'float') {
        styleName = 'cssFloat';
      }
      try {
        var computed = document.defaultView.getComputedStyle(element, '');
        return element.style[styleName] || computed ? computed[styleName] : null;
      } catch (e) {
        return element.style[styleName];
      }
  }

  // \s：空格 \uFEFF：字节次序标记字符 \xA0：禁止自动换行空白符，相当于html中的&nbsp;
  export const trim = function(string) {
    return (string || '').replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
  /* istanbul ignore next */
  const camelCase = function(name) {
    return name.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
      return offset ? letter.toUpperCase() : letter;
    });
  };



  export const on = (function() {
    if (document.addEventListener) {
      return function(element, event, handler) {
        if (element && event && handler) {
          element.addEventListener(event, handler, false);
        }
      };
    } else {
      return function(element, event, handler) {
        if (element && event && handler) {
          element.attachEvent('on' + event, handler);
        }
      };
    }
  })();

  /* istanbul ignore next */
  export const off = (function() {
    if (document.removeEventListener) {
      return function(element, event, handler) {
        if (element && event) {
          element.removeEventListener(event, handler, false);
        }
      };
    } else {
      return function(element, event, handler) {
        if (element && event) {
          element.detachEvent('on' + event, handler);
        }
      };
    }
  })();

  /* istanbul ignore next */
  export const once = function(el, event, fn) {
    var listener = function() {
      if (fn) {
        fn.apply(this, arguments);
      }
      off(el, event, listener);
    };
    on(el, event, listener);
  };

  export function debounce(func, delay) {
    let timer;
    return function (...args) {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        func.apply(this, args);
      }, delay)
    }
  }

let timeout = null
export function debounceTwo(fn, wait) {
    if (timeout !== null) clearTimeout(timeout)
    timeout = setTimeout(fn, wait)
}

  //从数组_arr中删除_obj对象
export function removeObjWithArr (_arr,_obj) {
	//debugger;
    var length = _arr.length;
    for(var i = 0; i < length; i++)
    {
        if(JSON.stringify(_arr[i]) == JSON.stringify(_obj))
        {
            if(i == 0)
            {
                _arr.shift(); //删除并返回数组的第一个元素
                return;
            }
            else if(i == length-1)
            {
                _arr.pop();  //删除并返回数组的最后一个元素
                return;
            }
            else
            {
                _arr.splice(i,1); //删除下标为i的元素
                return;
            }
        }
    }
};

//从数组_arr中删除_obj对象中属性keyName相同的
export function removeObjWithKey (_arr,_obj,keyName) {
	//debugger;
  var length = _arr.length;
  for(var i = 0; i < length; i++)
  {
      if(_arr[i][keyName] == _obj[keyName])
      {
          if(i == 0)
          {
              _arr.shift(); //删除并返回数组的第一个元素
              return;
          }
          else if(i == length-1)
          {
              _arr.pop();  //删除并返回数组的最后一个元素
              return;
          }
          else
          {
              _arr.splice(i,1); //删除下标为i的元素
              return;
          }
      }
  }
};

/**
 *
 * @param {*} arr 数组
 * @param {*} key 对象中的属性
 * @param {排序  asc 升序  desc 降序} order 默认升序
 */
export function cmpArrayByKey(arr,key,order='asc'){
  if(!arr || arr.length < 1){
    return;
  }
  if(!arr[0][key]){
    return;
  }
  let orderNum = 1;
  if(order == 'desc'){
    orderNum = -1;
  }
  function compare(key) {
    return function (a, b) {
      let value1 = a[key];
      let value2 = b[key];
      if(value1 < value2){
        return orderNum * -1;
      }
      if(value1 > value2){
          return orderNum * 1;
      }
      return 0;
    }
  }
  return arr.sort(compare(key));
}


export function getQueryVariable(){
  let query = window.location.search.substring(1);
  if(!query){
      query = window.location.hash;
      let wenIdx = query.indexOf('?');
      query = query.substr(wenIdx + 1);
  }
  //console.info(query);
  let vars = query.split("&");
  let qryMap = {};
  for (let i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      let value = pair[1];
      if(pair.length > 2){//针对这样的参数 token=V8x7/bXcqAw====3
          for(let j = 2; j < pair.length; j++){
              if(pair[j]){
                  value += pair[j];
              } else {
                  value += '=';
              }
          }
      }
      qryMap[pair[0]] = value;
  }
  return qryMap;
}

//判断是不是ASCII码
export function isAsciiChar(str){
  return ASCII_CHARS.test(str);
}

//判断当前客户端版本curVersion 是大于在versionCode
export function cmpClientVersion(curVersion,versionCode){
  if(!versionCode || !curVersion){
    return false;
  }
  //如果两个版本一样  则返回true
  if(curVersion == versionCode){//必须大于versionCode
    return false;
  }
  let retFlg = false;
  let curArr = curVersion.split('.');//当前客户端版本分解成数组，如2.20.41  分解成[2,20,41]
  let verArr = versionCode.split('.');//被比较的版本分解成数组
  let len = Math.min(curArr.length,verArr.length);
  for(let i = 0; i < len; i++){//循环版本号数组
    if(parseInt(curArr[i]) > parseInt(verArr[i])){//当前版本号转换成数值后大于被比较的版本
      retFlg = true;
      break;
    } else if(parseInt(curArr[i]) < parseInt(verArr[i])){//当前版本号转换成数值后小于被比较的版本
      retFlg = false;
      break;
    }
  }
  return retFlg;
}
//此处统一用AES加密
const urlPrefix = {
  //http://221.178.251.152:8080
  center1:'z3qN4/dDaQQ9oTLOh+R/CWeO+ZyTvT2Rys60zyqgEYY=',
  //http://183.207.195.94:8080
  center2:'hZPW5Nxpz7My1mXQjTHIfmp+HfcYhi/wtycwqL0JJBA=',
   //http://221.178.251.57:8080
  mapUrl:'z3qN4%2FdDaQQ9oTLOh%2BR%2FCXxaMdu5DbuFbpH%2BDcwSYa0%3D',
  
}
//获取解密后的URL
export function getRealUrl(key){
  if(key && urlPrefix[key]){
    return decrptParam(urlPrefix[key])
  }
}
//网址拼参数判断用？还是&号
export function appendParamToUrl(url,param){
  if(!url){
    return url;
  }
  if(~url.indexOf('?')){//URL链接中有?，则用&连接
    url += '&';
  }else {
    url += '?';
  }
  if(param){
    url += param;
  }
  return url;
}

// 加法
export function accAdd(data1, data2) {
  var r1, r2, m, c;
  try {
    r1 = data1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = data2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  c = Math.abs(r1 - r2);
  m = Math.pow(10, Math.max(r1, r2));
  if (c > 0) {
    var cm = Math.pow(10, c);
    if (r1 > r2) {
      data1 = Number(data1.toString().replace(".", ""));
      data2 = Number(data2.toString().replace(".", "")) * cm;
    } else {
      data1 = Number(data1.toString().replace(".", "")) * cm;
      data2 = Number(data2.toString().replace(".", ""));
    }
  } else {
    data1 = Number(data1.toString().replace(".", ""));
    data2 = Number(data2.toString().replace(".", ""));
  }
  return (data1 + data2) / m;
}

// 减法
export function numSub(data1, data2) {
  var num, num1, num2;
  var precision;// 精度
  try {
    num1 = data1.toString().split(".")[1].length;
  } catch (e) {
    num1 = 0;
  }
  try {
    num2 = data2.toString().split(".")[1].length;
  } catch (e) {
    num2 = 0;
  }
  num = Math.pow(10, Math.max(num1, num2));
  precision = (num1 >= num2) ? num1 : num2;
  return ((data1 * num - data2 * num) / num).toFixed(precision);
}


// 乘法
export function accMulti(data1, data2) {
  var baseData = 0;
  try {
    baseData += data1.toString().split(".")[1].length;
  } catch (e) {
  }
  try {
    baseData += data2.toString().split(".")[1].length;
  } catch (e) {
  }
  return Number(data1.toString().replace(".", "")) * Number(data2.toString().replace(".", "")) / Math.pow(10, baseData);
}


// 除法
export function division(arg1, arg2) {
  var t1 = 0, t2 = 0, r1, r2;
  try {
    t1 = new String(arg1).split(".")[1].length;
  } catch (e) {
  }
  try {
    t2 = arg2.toString().split(".")[1].length;
  } catch (e) {
  }
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
//放大倍数后两个数相除 后，乘以两个小数位数长度相减后的10的次幂
  var newData = accMulti((r1 / r2), Math.pow(10, t2 - t1));
//保留2个小数位数：
  return newData.toFixed(2)
}
export function getRandomStr(range=100000){
  let rangeNum = parseInt(range,16);
  return (((1+Math.random())*rangeNum)|0).toString(16).substring(1);  
}

export function getEncKey(input){
  var output = '';
  var mapping = {
      'd': 'E',
      'g': '0',
      'a': '9',
      'b': 'Y',
      'c': '7',
      'h': '0',
      'i': 'A',
      'j': '0',
      'k': 'n',
      'l': 'y',
      'e': 'g',
      'o': 'I',
      'p': '9',
      'f': '8',
      'm': '3',
      'n': 'T',

  };
  for (var i = 0; i < input.length; i++) {
      output += mapping[input[i]];
  }
  return output;
}